package com.nineclock.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserMapper userMapper;

    @Override
    public Boolean checkExists(String mobile) {
        LambdaQueryWrapper<SysUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getMobile,mobile);
        Integer count = userMapper.selectCount(queryWrapper);
        return count==1;
    }

    @Autowired
    SmsService smsService;
    @Override
    public long register(SysRegisterDTO registerDTO) {
        if(registerDTO == null || registerDTO.getMobile() == null || registerDTO.getCheckcode() == null || registerDTO.getPassword() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //调用的 短信验证的接口 校验验证码
        Boolean flag = smsService.verify(
                registerDTO.getMobile(),
                SMSConstant.SMS_TYPE_REGISTER, registerDTO.getCheckcode());
        if(!flag){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        //创建用户
        SysUser user = new SysUser();
        //保存加密后的密码
        user.setPassword(new BCryptPasswordEncoder().encode(registerDTO.getPassword()));
        user.setCreateTime(new Date());
        user.setMobile(registerDTO.getMobile());
        user.setStatus((short)1);


        userMapper.insert(user);
        return user.getId();
    }
}
